<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-primary border-b-2 border-primary py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">{{ cartStore.cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg bg-primary/10 text-primary font-medium">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <section class="mb-8">
        <div class="text-center">
          <h1 class="text-3xl md:text-4xl font-bold text-gray-800 mb-4">图书资讯</h1>
          <p class="text-gray-600 text-lg max-w-2xl mx-auto">
            获取最新的图书资讯、作者访谈、阅读指南和行业动态，让您的阅读之旅更加精彩
          </p>
        </div>
      </section>

      <!-- 资讯分类导航 -->
      <section class="mb-8">
        <div class="flex flex-wrap justify-center gap-4">
          <button
            v-for="category in newsCategories"
            :key="category.id"
            @click="handleCategoryChange(category.id)"
            :class="[
              'px-6 py-2 rounded-full font-medium transition-all duration-300',
              activeCategory === category.id
                ? 'category-btn-active'
                : 'category-btn-inactive'
            ]"
          >
            {{ category.name }}
          </button>
        </div>
      </section>

      <!-- 资讯列表 -->
      <section class="mb-12">
        <!-- 加载状态 -->
        <div v-if="loading" class="flex justify-center items-center py-12">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
          <span class="ml-3 text-gray-600">加载中...</span>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!allNews.length" class="text-center py-12">
          <div class="text-gray-400 text-6xl mb-4">
            <i class="fas fa-newspaper"></i>
          </div>
          <h3 class="text-xl font-medium text-gray-600 mb-2">暂无资讯</h3>
          <p class="text-gray-500">请稍后再试或切换其他分类</p>
        </div>

        <!-- 资讯列表 -->
        <div v-else class="space-y-4">
          <article
            v-for="article in paginatedNews"
            :key="article.id"
            class="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all duration-300 border border-gray-100 cursor-pointer"
            @click="readArticle(article.id)"
          >
            <div class="flex flex-col md:flex-row gap-4">
              <img
                :src="article.image"
                :alt="article.title"
                class="w-full md:w-32 h-32 object-cover rounded-lg"
              >
              <div class="flex-1">
                <div class="flex items-center gap-2 mb-2">
                  <span class="bg-primary/10 text-primary text-xs font-medium px-2 py-1 rounded">{{ article.category }}</span>
                </div>
                <h3 class="font-bold text-xl mb-2 text-gray-800 hover:text-primary transition-colors">{{ article.title }}</h3>
                <p class="text-gray-600 mb-3 line-clamp-2">{{ article.summary }}</p>
                <p class="text-gray-600 mb-3 line-clamp-2"><span class="text-gray-500 text-sm">发布时间：{{ article.publishDate }}</span></p>
                <div class="flex items-center justify-between">
                  <span class="text-gray-500 text-sm">作者：{{ article.author }}</span>
                  <div class="flex items-center text-gray-500 text-sm">
                    <i class="fas fa-eye mr-1"></i>
                    <span>{{ article.views }}</span>
                  </div>
                </div>
              </div>
            </div>
          </article>
        </div>

        <!-- 分页组件 -->
        <div v-if="!loading && totalNews > 0" class="flex justify-center mt-8">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalNews"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination-custom"
            prev-text="上一页"
            next-text="下一页"
          />
        </div>
      </section>

      <!-- 订阅资讯 -->
      <section class="mb-16 bg-white rounded-2xl p-6 shadow-sm">
        <div class="flex flex-col md:flex-row items-center justify-between">
          <div class="mb-4 md:mb-0">
            <h2 class="text-xl font-bold text-dark mb-2">订阅我们的图书资讯</h2>
            <p class="text-gray-600">第一时间获取新书资讯、作者访谈和阅读指南</p>
          </div>
          <div class="flex w-full md:w-auto">
            <input
              type="email"
              placeholder="请输入您的邮箱地址"
              class="border border-gray-300 focus:border-primary rounded-l-full px-4 py-2 w-full md:w-64 outline-none email-input"
            />
            <button class="text-white rounded-r-full px-6 py-2 shadow-md whitespace-nowrap subscribe-btn">
              立即订阅
            </button>
          </div>
        </div>
      </section>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
            <div class="flex space-x-4 mt-4">
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weixin text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weibo text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-qq text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fas fa-envelope text-xl"></i></a>
            </div>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">读者推荐</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-clock text-primary mr-3"></i>
                <span class="text-gray-400">周一至周日 9:00-22:00</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
          <div class="text-gray-500 text-sm mb-4 md:mb-0">
            © {{ new Date().getFullYear() }} 书香阁 版权所有 | 京ICP备12345678号
          </div>
          <div class="flex space-x-4">
            <a href="#" class="text-gray-500 text-sm hover:text-primary">隐私政策</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">使用条款</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">网站地图</a>
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import BackToTop from '@/components/BackToTop.vue'
import { newsAPI } from '@/api/news.js'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const activeCategory = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const loading = ref(false)
const allNews = ref([])
const totalNews = ref(0)

// 资讯分类数据
const newsCategories = ref([
  { id: 0, name: '全部' }
])

// 加载新闻分类
const loadNewsCategories = async () => {
  try {
    const response = await newsAPI.getNewsCategories()
    const categories = response.data || []
    newsCategories.value = [
      { id: 0, name: '全部' },
      ...categories.map(cat => ({ id: cat.id, name: cat.name }))
    ]
  } catch (error) {
    console.error('加载新闻分类失败:', error)
  }
}

// API调用方法
const loadNewsList = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }

    // 如果有分类筛选
    if (activeCategory.value !== 0) {
      const categoryName = newsCategories.value.find(cat => cat.id === activeCategory.value)?.name
      if (categoryName && categoryName !== '全部') {
        params.category = categoryName
      }
    }

    const response = await newsAPI.getNewsList(params)
    allNews.value = response.data.records || []
    totalNews.value = response.data.total || 0
  } catch (error) {
    console.error('加载新闻列表失败:', error)
    ElMessage.error('加载新闻列表失败')
    allNews.value = []
    totalNews.value = 0
  } finally {
    loading.value = false
  }
}

// 计算属性：格式化新闻数据
const paginatedNews = computed(() => {
  return allNews.value.map(news => ({
    id: news.id,
    title: news.title,
    summary: news.summary,
    author: news.author,
    publishDate: formatDate(news.publishTime || news.createdAt),
    category: getCategoryFromSummary(news.summary),
    image: getImageUrl(news.cover),
    views: formatViewCount(news.viewCount),
    content: news.content
  }))
})

// 格式化浏览量
const formatViewCount = (count) => {
  if (!count) return '0'
  if (count >= 1000) {
    return (count / 1000).toFixed(1) + 'k'
  }
  return count.toString()
}

// 从摘要中提取分类（临时方案）
const getCategoryFromSummary = (summary) => {
  if (!summary) return '其他'
  if (summary.includes('推荐') || summary.includes('新书')) return '新书推荐'
  if (summary.includes('访谈') || summary.includes('作者')) return '作者访谈'
  if (summary.includes('阅读') || summary.includes('指南')) return '阅读指南'
  if (summary.includes('行业') || summary.includes('动态')) return '行业动态'
  if (summary.includes('书评') || summary.includes('评论')) return '书评推荐'
  return '其他'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const readArticle = (articleId) => {
  router.push(`/news/${articleId}`)
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadNewsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNewsList()
}

// 分类切换
const handleCategoryChange = (categoryId) => {
  activeCategory.value = categoryId
  currentPage.value = 1
  loadNewsList()
}

const goToCart = () => {
  router.push('/cart')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f94fa5368ec54a9a1fafd8c376d0aa53.png'

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `http://localhost:8081/api${url}`
}

// 组件挂载时加载数据
onMounted(() => {
  loadNewsCategories()
  loadNewsList()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.text-secondary {
  color: var(--secondary);
}

.bg-secondary\/30 {
  background-color: rgba(255, 209, 220, 0.3);
}

.text-accent {
  color: var(--accent);
}

.text-dark {
  color: var(--dark);
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:bg-primary\/10:hover {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}

/* 卡片悬停效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 分类按钮样式 */
.category-btn-active {
  background-color: #FF6B8B !important;
  color: white !important;
  box-shadow: 0 4px 12px rgba(255, 107, 139, 0.3) !important;
}

.category-btn-inactive {
  background-color: white !important;
  color: #6b7280 !important;
  border: 1px solid #e5e7eb !important;
}

.category-btn-inactive:hover {
  background-color: rgba(255, 107, 139, 0.1) !important;
  color: #FF6B8B !important;
}

/* 订阅按钮悬停效果 */
.subscribe-btn {
  transition: all 0.3s ease;
  background-color: #FF8FA3 !important;
}

.subscribe-btn:hover {
  transform: translateY(-3px) !important;
  background-color: #ff789a !important;
  box-shadow: 0 8px 15px rgba(255, 107, 139, 0.3) !important;
}

/* 分页组件自定义样式 */
.pagination-custom :deep(.el-pagination) {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination-custom :deep(.el-pagination .el-pager li) {
  background-color: white;
  border: 1px solid #e5e7eb;
  color: #6b7280;
  margin: 0 2px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.pagination-custom :deep(.el-pagination .el-pager li:hover) {
  background-color: rgba(255, 107, 139, 0.1);
  color: #FF6B8B;
  border-color: #FF6B8B;
}

.pagination-custom :deep(.el-pagination .el-pager li.is-active) {
  background-color: #FF6B8B;
  color: white;
  border-color: #FF6B8B;
}

.pagination-custom :deep(.el-pagination .btn-prev),
.pagination-custom :deep(.el-pagination .btn-next) {
  background-color: white;
  border: 1px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.pagination-custom :deep(.el-pagination .btn-prev:hover),
.pagination-custom :deep(.el-pagination .btn-next:hover) {
  background-color: rgba(255, 107, 139, 0.1);
  color: #FF6B8B;
  border-color: #FF6B8B;
}

.pagination-custom :deep(.el-select .el-input .el-input__wrapper) {
  border-radius: 8px;
  border-color: #e5e7eb;
}

.pagination-custom :deep(.el-select .el-input .el-input__wrapper:hover) {
  border-color: #FF6B8B;
}

/* 自定义分页文本样式 */
.pagination-custom :deep(.el-pagination__total) {
  color: #6b7280;
  font-weight: 500;
}

.pagination-custom :deep(.el-pagination__jump) {
  color: #6b7280;
}

.pagination-custom :deep(.el-select__caret) {
  color: #6b7280;
}
</style>
